<template>
  <div class="edit-ask-leave-datetime ask-leave-info">
    <div class="scroll-box">
      <group>
        <cell-box class="cellbox-item">
          <flexbox>
            <flexbox-item class="title" :span="4">
              请假开始日期<span class="require-item">*</span>
            </flexbox-item>
            <flexbox-item class="value date-pciker" :span="8">
              <datetime v-model="startDate"
              :start-date="datePickerConfig.startDateConfig.startDate"
              :end-date="datePickerConfig.startDateConfig.endDate"
              placeholder="请选择请假开始日期" :format="datePickerConfig.format"
              :min-hour="datePickerConfig.workStartHour"
              :max-hour="datePickerConfig.workEndHour"
              :minuteList="datePickerConfig.startDateConfig.minuteList"
              @on-change="dateChange('startDate')"
              ref="startDateDom"
              clear-text="请假开始日期" class="datetime"></datetime>
            </flexbox-item>
          </flexbox>
        </cell-box>
        <cell-box class="cellbox-item">
          <flexbox>
            <flexbox-item class="title" :span="4">
              请假结束日期<span class="require-item">*</span>
            </flexbox-item>
            <flexbox-item class="value date-pciker" :span="8">
              <datetime v-model="endDate"
              :start-date="datePickerConfig.endDateConfig.startDate"
              :end-date="datePickerConfig.endDateConfig.endDate"
              placeholder="请选择请假结束日期" :format="datePickerConfig.format"
              :max-hour="datePickerConfig.workEndHour"
              :min-hour="datePickerConfig.workStartHour"
              :minuteList="datePickerConfig.endDateConfig.minuteList"
              @on-change="dateChange('endDate')"
              ref="endDateDom"
              clear-text="请假结束日期" class="datetime"></datetime>
            </flexbox-item>
          </flexbox>
        </cell-box>
        <cell-box class="cellbox-item">
          <flexbox>
            <flexbox-item class="title" :span="4">
              请假小时数<span class="require-item">*</span>
            </flexbox-item>
            <flexbox-item class="value leave-minute" :span="8">
              <input type="tel" v-model="applyTimeText" readonly
                    placeholder="请输入小时数（共_天）">
              <input type="hidden" v-model="applyMinute" >
            </flexbox-item>
          </flexbox>
        </cell-box>
        <cell-box class="cellbox-item">
          <flexbox align="flex-start">
            <flexbox-item class="title" :span="4">
              缩短日期原因<span class="require-item">*</span>
            </flexbox-item>
            <flexbox-item class="value edit-date-reason" :span="8">
              <textarea v-model="editApplyDateReason" placeholder="请输入缩短日期原因"></textarea>
            </flexbox-item>
          </flexbox>
        </cell-box>
      </group>
      <div class="button-box vux-1px-t vux-1px-b">
        <button class="submit-btn" @click="submitClick">提交</button>
      </div>
    </div>
    <!-- 加载中 -->
    <loading class="loading-mask" :show="loadingShow" text="加载中..."></loading>
    <!-- 提示彈窗 -->
    <div v-transfer-dom>
      <confirm v-model="turndownShow"
        class="turndown-confirm turndown-alert" title="提示" confirm-text="确认" :show-cancel-button="false">
        <p>{{turndownText}}</p>
      </confirm>
    </div>
  </div>
</template>

<script>
  import { Group, CellBox, Flexbox, FlexboxItem, dateFormat, Datetime, TransferDom, Confirm, Loading } from 'vux';
  import qs from 'qs';
  import { getMinutes } from '@/assets/js/computedMinutes.js';
  export default {
    name: 'EditAskLeaveDatetime',
    components: {
      Group,
      CellBox,
      Flexbox,
      FlexboxItem,
      Datetime,
      Confirm,
      Loading
    },
    directives: {
      TransferDom
    },
    mounted () {
      this.pageParams = JSON.parse(this.$route.query.editAskLeaveDatetimeInfo);
      let startDate = dateFormat(this.pageParams.Content.StartDate.replace(/T/g, ' '), 'YYYY-MM-DD HH:mm');
      let endDate = dateFormat(this.pageParams.Content.EndDate.replace(/T/g, ' '), 'YYYY-MM-DD HH:mm');
      this.startDate = startDate;
      this.endDate = endDate;
      this.$refs.startDateDom.currentValue = startDate;
      this.$refs.endDateDom.currentValue = endDate;
      this.applyDay = this.pageParams.Content.Day;
      this.applyMinute = this.pageParams.Content.Minute;
      this.applyTimeText = `${((this.applyMinute)/60).toFixed(2)}小时（共${this.applyDay}天）`;
      // this.editApplyDateReason = this.pageParams.Content.EditApplyDateReason; // 隱藏縮短原因
      this.datetimeInit();
    },
    data () {
      return {
        pageParams: {
        },
        startDate: '',
        endDate: '',
        datePickerConfig: {
          format: 'YYYY-MM-DD HH:mm', // 日期格式
          workEndHour: 19, // 下班時間
          workStartHour: 9, // 上班時間
          startDateConfig: {
            startDate: '',
            endDate: '',
            minuteList: ['00', '15', '30', '45']
          },
          endDateConfig: {
            startDate: '',
            endDate: '',
            minuteList: ['00', '15', '30', '45']
          }
        },
        applyTimeText: '', // 請假分鐘+天數 顯示
        applyDay: '', // 請假天数【提交】
        applyMinute: '',  // 請假分鐘【提交】
        workHours: this.getUserInfo().IsBusiness === 'S' ? 9 : 7.5,
        turndownShow: false,
        turndownText: '',
        loadingShow: false,
        editApplyDateReason: '',
        required: ['StartDate', 'EndDate', 'Minute', 'EditApplyDateReason']
      };
    },
    methods: {
      // 日期更改時的回調
      dateChange: function (dateType) {
        if (this.startDate && this.endDate) {
          this.applyTimeText = getMinutes(this.startDate, this.endDate, this.getUserInfo().IsBusiness);
          this.computeDays();
        }
        this.checkDateRange();
      },
      // 檢查請假開始日期是否大於請假結束日期
      checkDateRange: function () {
        let startDate = new Date(this.startDate.replace(/ /g, 'T'));
        let endDate = new Date(this.endDate.replace(/ /g, 'T'));
        if (startDate > endDate) {
          this.endDate = '';
          this.$refs.endDateDom.currentValue = this.endDate;
          this.turndownText = '请假开始日期不能大于请假结束日期';
          this.turndownShow = true;
        }
      },
      inputMinute: function () {
        if (this.applyTimeText && (/[^0-9]/).test(this.applyTimeText)) {
          let newStr = this.applyTimeText.replace(/[^0-9]/g, '');
          this.applyTimeText = newStr;
        }
      },
      // 请假分钟失焦自动计算请假天数
      computeDays: function () {
        let applyTimeNumber = parseInt(this.applyTimeText);
        let startDay = new Date(this.startDate.replace(/-/g, '/') + ':00').getDate();
        let endDay = new Date(this.endDate.replace(/-/g, '/') + ':00').getDate();
        if (this.applyTimeText === '') {
          return false;
        }
        if (applyTimeNumber > 85440) {
          alert('请假不能超过178天');
          this.applyTimeText = '';
          return false;
        } else if (applyTimeNumber < 0) {
          this.applyTimeText = '';
          return false;
        }
        this.applyMinute = this.applyTimeText;
        this.applyDay = (this.applyMinute / (this.workHours * 60)).toFixed(2);
        if (endDay - startDay === 0 && this.applyDay > 1) {
          this.applyDay = 1;
        }
        this.applyTimeText = `${((this.applyMinute)/60).toFixed(2)}小时（共${this.applyDay}天）`;
      },
      // 获取焦点清空请假分钟
      clearApplyMinute: function () {
        this.applyTimeText = '';
        this.applyMinute = '';
        this.applyDay = '';
      },
      datetimeInit: function () {
        let startDate = this.formatDateToYYYYMMDD(this.pageParams.Content.StartDate.replace(/T/g, ' '));
        let endDate = this.formatDateToYYYYMMDD(this.pageParams.Content.EndDate.replace(/T/g, ' '));
        this.datePickerConfig.startDateConfig.startDate = startDate;
        this.datePickerConfig.startDateConfig.endDate = endDate;
        this.datePickerConfig.endDateConfig.startDate = startDate;
        this.datePickerConfig.endDateConfig.endDate = endDate;
      },
      formatDateToYYYYMMDD: function (date) {
        if (!date) return;
        return dateFormat(date, 'YYYY-MM-DD');
      },
      // 檢測請假分鐘是否0
      checkMinute: function (minute) {
        if (minute === 0) {
            this.turndownText = '请假时长不能为0';
            this.turndownShow = true;
          return false;
        } else {
          return true;
        }
      },
      submitClick: function () {
        let postData = {
          data: {
            KeyId: this.pageParams.KeyId,
            StartDate: this.startDate,
            EndDate: this.endDate,
            Day: this.applyDay,
            Minute: this.applyMinute,
            EditApplyDateReason: this.editApplyDateReason
          }
        };

        for (let prop in this.required) {
          let propName = this.required[prop];
          if (postData.data[propName] === '' || postData.data[propName] === null) {
            this.turndownText = '请时输入必填项';
            this.turndownShow = true;
            return false;
          }
        }
        if (this.checkMinute(postData.data.Minute) === false) {
          return false;
        }
        this.loadingShow = true;
        this.axios.post('/Process/EditAskForLeaveDatetime', qs.stringify(postData))
        .then((res) => {
          this.loadingShow = false;
          if (res.data.IsSuccess === true) {
            this.turndownText = '修改成功';
            this.turndownShow = true;
            this.$router.replace({
              name: 'ApplicationDetail',
              query: {
                item: JSON.stringify({
                  KeyId: this.pageParams.KeyId
                })
              }
            });
          } else {
            this.turndownText = res.data.ExMessage;
            this.turndownShow = true;
          }
        })
        .catch(() => {
          this.loadingShow = false;
          this.turndownText = '修改请求时发生错误';
          this.turndownShow = true;
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  @import '../../assets/style/variable';

  .cellbox-item{
    padding: 0 15px;
    &:before{
      border-color: #e6e6e6;
    }
    .title{
      color: #666;
      font-size: getRem(28);
      padding: getRem(32) 0;
    }
    .value{
      font-size: getRem(28);
    }
    .date-pciker {
      padding: getRem(32) 0;
      a {
        padding: getRem(32) 0;
        display: inline;
        color: #ddd;

        &:before {
          content: none;
        }
      }
      .has-value {
        color: #333;
      }
      .separation-symbol {
        color: #666;
      }
    }
    .leave-minute{
      input{
        display: block;
        width: calc(100% - 15px);
        border: 0;
        padding: getRem(32) 0;
        line-height: getRem(38);
        // line-height: getRem(102);
        font-size: getRem(28);
        outline: none;
        &::placeholder{
          color: #ddd;
        }
      }
    }
    .edit-date-reason{
      textarea{
        display: block;
        width: calc(100% - 15px);
        border: 0;
        padding: getRem(32) 0;
        line-height: getRem(38);
        // line-height: getRem(102);
        font-size: getRem(28);
        outline: none;
        &::placeholder{
          color: #ddd;
        }
      }
    }
  }
  .button-box{
    margin-top: getRem(20);
    &:after{
      border-color: #d9d9d9;
    }
    &:before{
      border-color: #d9d9d9;
    }
    .submit-btn{
      display:block;
      width: calc(100% - 30px);
      width: 100%;
      font-size: getRem(32);
      line-height: getRem(100);
      border: 0;
      background: #fff;
    }
  }
</style>
